package com.dao;

import java.util.Collections;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.form.QueryForm;
import com.hibernate.HibernateSessionFactory;
import com.model.Order;
import com.model.Orderdetail;

/**
 * 对订单相关表模型的增删改查
 *  
 * @author 0912652
 */

public class OrderDao {
	
	public List<Orderdetail> findOrderDtilsByRid(int rid){
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(Orderdetail.class);
		Criteria cr = criteria.createCriteria("room");
		
		cr.add(Restrictions.eq("rid", rid));
		
		List<Orderdetail> orderdetails = criteria.list();
		
		return orderdetails;
	}
	
	public List<QueryForm> getQueryForms(int rid){
		List<Orderdetail> orderdetails = findOrderDtilsByRid(rid);
		List<QueryForm> queryForms = Collections.emptyList();
		QueryForm queryForm = new QueryForm();
		for (Orderdetail orderdetail : orderdetails) {
			queryForm.setBegin(orderdetail.getCtime());
			queryForm.setEnd(orderdetail.getLtime());
			queryForm.setId(orderdetail.getRoom().getRid());
			
			queryForms.add(queryForm);
		}
		
		return queryForms;
		
	}
	
	public Order saveOrder(List<Orderdetail> orderdetails, Order order){
		 Session session = HibernateSessionFactory.getSession();
		 try {
			 //开启事务
			 session.beginTransaction();
			 
			 session.save(order);
			 for (Orderdetail orderdetail : orderdetails) {
				session.save(orderdetail);
			}
			session.getTransaction().commit();
			return order;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		}finally {
			HibernateSessionFactory.closeSession();
		}
		 
	}

}
